﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FisheryPlatform.Entity;
using FisheryPlatform.Bussiness.Post;
using FisheryPlatform.Bussiness.Option;

namespace FisheryPlatform.Web.Admin.Posts
{
    public partial class Index : System.Web.UI.Page
    {
        protected List<PostsEntity> PostList = null;
        protected List<UsersEntity> UserList = null;
        protected Dictionary<long, List<TermEntity>> TermList = null;
        protected List<string> HotPostTopList = null;
        protected List<string> HotPostHomeList = null;
        protected Dictionary<int, int> AmountList = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            InitData();
        }

        private void InitData()
        {
            HotPostTopList = OptionManager.GetByOptionName(OptionNameConstants.Posts_Top).Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
            HotPostHomeList = OptionManager.GetByOptionName(OptionNameConstants.Posts_Home).Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
            AmountList = PostManager.GetAmountGroupByStatus();
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            #region
            var sqlWhereString = "";
            var pageIndex = 1;
            if (int.TryParse(Request.QueryString["pi"], out pageIndex) == false)
            {
                pageIndex = 1;
            }
            var pageSize = 25;
            var pageCount = 0;
            GetSearchCondition(out sqlWhereString);
            PostList = PostManager.Search(sqlWhereString, pageIndex, pageSize, out pageCount);

            var userIds = "";
            var postIds = "";
            PostList.ForEach(item =>
            {
                postIds += item.PostId + ",";
                userIds += item.AuthorId + ",";
            });
            TermList = PostManager.GetPostTermRelationshipsByPostIds(postIds);
            UserList = FisheryPlatform.Bussiness.Account.UserManager.GetListByUserIds(userIds);

            this.pb_PageBar.PbModel.CurrentIndex = pageIndex;
            this.pb_PageBar.PbModel.PageCount = pageCount;
            this.pb_PageBar.PbModel.PageSize = pageSize;
            this.pb_PageBar.PbModel.IsForAjax = true;
            this.pb_PageBar.PbModel.AjaxPageClickCallback = "PageChanged({index})";
            #endregion
        }

        protected string GetCateNames(long postId)
        {
            return GetTermNames(postId, TermTaxonomyEnum.Cate);
        }

        protected string GetTagNames(long postId)
        {
            return GetTermNames(postId, TermTaxonomyEnum.Tag);
        }

        private string GetTermNames(long postId, TermTaxonomyEnum taxonomy)
        {
            #region
            var result = "";
            if (TermList.ContainsKey(postId))
            {
                TermList[postId].ForEach(item =>
                {
                    if (item.Taxonomy == taxonomy)
                    {
                        result += HttpUtility.HtmlEncode(item.Name) + "<br/>";
                    }
                });
            }
            return result;
            #endregion
        }

        protected string UserName(long userId)
        {
            #region
            var result = "";
            foreach (var user in UserList)
            {
                if (user.UserId == userId)
                {
                    result = user.LoginName;
                    break;
                }
            }
            return result;
            #endregion
        }

        private void GetSearchCondition(out string sqlWhereString)
        {
            #region
            sqlWhereString = " 1=1 ";
            long cateId = 0;
            if (long.TryParse(Request.QueryString["cate"], out cateId) && cateId > 0)
            {
                sqlWhereString += " and postId in( select pt.PostId " +
                                  "    from dbo.Terms t right join dbo.PostTermRelationships pt " +
                                  "        on t.TermId=pt.TermId " +
                                  "   where pt.TermId=" + cateId + " )";
            }
            else
            {
                int status = 1;
                if (int.TryParse(Request.QueryString["status"], out status) && status >= 0)
                {
                    sqlWhereString += " and status=" + status;
                }
                else
                {
                    sqlWhereString += " and status!=" + (int)PostStatusEnum.Trash;
                }

                if (string.IsNullOrEmpty(Request.QueryString["show_hot"]) == false)
                {
                    sqlWhereString += " and postId in(" + Request.QueryString["show_hot"] + ")";
                }
            }
            #endregion
        }

        protected int GetTotalAmount()
        {
            #region
            var total = 0;
            foreach (var item in AmountList.Values)
            {
                total += item;
            }
            if (AmountList.ContainsKey((int)PostStatusEnum.Trash))
            {
                total -= AmountList[(int)PostStatusEnum.Trash];
            }
            return total;
            #endregion
        }
    }
}